﻿using Innoapps.FileTransfer.Helpers;
using Innoapps.FileTransfer.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Innoapps.FileTransfer
{
    public class Instance
    {
        #region Variables
        public XmlSerializerHelper<Models.Transfer> xmlHelperData = new XmlSerializerHelper<Models.Transfer>();
        public Models.Transfer transfer;
        public Settings settings;
        #endregion



        #region Constructors
        public Instance()
        {

        }

        public Instance(XmlDocument xmlDoc, Settings settings)
        {
            transfer = xmlHelperData.Read(xmlDoc, "http://innoapps.co.uk/FileTransfer/Transfer");
        }

        #endregion

        #region Methods
        public void Execute(string Activity, string Action) {

            // Get a reference to this assembly
            Assembly assembly = Assembly.GetCallingAssembly();
            // Get a reference to the activity class
            Type type = assembly.GetType(assembly.FullName + "." + Activity);
            MethodInfo methodInfo;
            
            // If the activity class is found then call the method
            if(type != null)
            {
                // Get the method
                methodInfo = type.GetMethod(Action);

                // Determine whether the method accepts a parameter
                ParameterInfo[] parameters = methodInfo.GetParameters();

                // Get a reference to the existing class instance
                object classInstance = this.GetType()
                    .GetProperty(Activity.Split('.')[0] == "Providers" ? "settings" : "transfer")
                    .GetType()
                    .GetProperty(Activity.Split('.')[1])
                    .GetValue(this);

                // IF the method does not accept parameters then invoke the method
                if (parameters.Length == 0)
                {
                    methodInfo.Invoke(classInstance, null);
                }
                // If the method acccepts parameters then pass the transfer ID when invoking the method
                else
                {
                    // Create a parameter array containing the transfer id
                    object[] parametersArray = new object[] { transfer.Id };

                    // Invoke the method passing the parameter array
                    methodInfo.Invoke(classInstance, parametersArray);
                }


            }

        }
        #endregion




    }
}
